import React, { Component } from 'react';
import { Form, Button } from 'antd';
import { connect } from 'dva';
import cls from 'classnames';
import { formatMessage } from 'umi-plugin-react/locale';
import { utils, Animate } from 'suid';
import LoginForm from './Form';
import styles from './index.less';

@connect(({ user, loading }) => ({ user, loading }))
@Form.create()
class Login extends Component {
  static loginReqId = utils.getUUID();

  state = {
    showVertifCode: false,
  };

  componentDidMount() {
    document.addEventListener('keydown', this.onKeyDown);
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.onKeyDown);
  }

  onKeyDown = e => {
    if (e.keyCode === 13) {
      this.login();
    }
  };

  login = e => {
    const { dispatch } = this.props;
    this.loginFormRef.onSubmit().then(values => {
      dispatch({
        type: 'user/userLogin',
        payload: { ...values },
      });
    });
    if (e) {
      e.preventDefault();
    }
  };

  render() {
    const { loading, user } = this.props;
    const { verifyCode } = user;
    const { showVertifCode } = this.state;
    const isLoading = loading.effects['user/userLogin'];

    return (
      <div className={styles['container-box']}>
        <div className={cls('form-logo', 'horizontal')}>
          <Animate type="fadeInLeft" delay={200}>
            J
          </Animate>
          <Animate type="tada" delay={400} duration={1500}>
            Y
          </Animate>
          <Animate type="tada" delay={400} duration={1500}>
            Y
          </Animate>
          <Animate type="fadeInRight" delay={200}>
            P
          </Animate>
        </div>
        <div className="login-form-title">
          <Animate type="flipInY" delay={400}>
            <span className="title">机域优品</span>
          </Animate>
        </div>

        <LoginForm
          onRef={inst => {
            this.loginFormRef = inst;
          }}
          loginReqId={this.loginReqId}
          verifyCode={verifyCode}
          loading={isLoading}
          showVertifCode={showVertifCode}
        >
          <Button
            loading={isLoading}
            type="primary"
            size="large"
            onClick={this.login}
            className="login-form-button"
          >
            {!isLoading
              ? formatMessage({ id: 'login.login', desc: '登录' })
              : formatMessage({ id: 'login.loginning', desc: '登录中...' })}
          </Button>
        </LoginForm>
      </div>
    );
  }
}
export default Login;
